package com.wyx.controller;

import com.sun.xml.internal.bind.v2.model.core.ID;
import com.wyx.pojo.Books;
import com.wyx.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService  bookService;

    @GetMapping("/allBook")
    public String list(Model model){
        List<Books> books = bookService.queryAllBook();
        model.addAttribute("list",books);
        return "allBook";
    }

    //去新增的页面
    @GetMapping("/toAddBook")
    public String toAdd(){
        return "addBook";
    }

    @PostMapping("/addBook")
    public String addBook(Books books){
        int i = bookService.addBook(books);
        return "redirect:/book/allBook";
    }


    @GetMapping("/del/{id}")
    //@PathVariable 中的值 应该是浏览器地址上的值 获得这个值 给 service层调用
    public String delete(@PathVariable("id") int id){

        bookService.deleteBookById(id);

        return "redirect:/book/allBook";
    }

    //去更新页面
    @GetMapping("/toUpdateBook/{id}")
    public String toUpDate(@PathVariable int id,Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);
        return "updateBook";
    }

    @PostMapping("/updateBook")
    public String updateBook(Books books){
        bookService.updateBook(books);

        System.out.println("更新成功!!!");
        return "redirect:/book/allBook";
    }

    //条件查询书籍
    @GetMapping("/queryBook")
    public String queryBook(String queryBookName,Model model){
        Books books = bookService.queryBookByName(queryBookName);
        List<Books> list = new ArrayList<Books>();
        list.add(books);

        if(books==null){
            list=bookService.queryAllBook();
            model.addAttribute("message","未查询到,已显示全部书籍信息");
        }



        model.addAttribute("list",list);
        //注意这里不能使用重定向到allBook页面了
        return "allBook";
    }

    //返回到书籍列表
    @RequestMapping("/toAllBook")
    public String toAllBooks(){
        return "redirect:/book/allBook";
    }


}
